﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace Algobox.JuicyLib.SQL.LiquidView
{
    public static class LiquidViewHelper
    {
        private static LiquidViewLinqDataContext _dbLinq;

        public static LiquidViewLinqDataContext LiquidViewLinq
        {
            get
            {
                if (_dbLinq == null)
                    _dbLinq = new LiquidViewLinqDataContext();

                return _dbLinq;
            }
            set 
            { 
                _dbLinq = value; 
            }
        }

        const int CURRENCYID_GBP = 1280;
        const int CURRENCYID_EUR = 1281;
        const int CURRENCYID_USD = 1282;

        public static void LogException(string category, string message)
        {
            LiquidViewLinq.ExceptionHandlerThrow(category, message, null);
        }

        public static void LogException(string category, string messageFormat, params object[] data)
        {
            LiquidViewLinq.ExceptionHandlerThrow(category, String.Format(messageFormat, data), null);
        }

        public static void LogException(string category, string message, int intValue)
        {
            LiquidViewLinq.ExceptionHandlerThrow(category, message, intValue);
        }


        public static void LogGeneral(string category, string description)
        {
            LiquidViewLinq.LogGeneral(category, String.Empty, String.Empty, description, null, null, null, null, null, null);
        }

        public static void LogGeneral(string category, string action, string description)
        {
            LiquidViewLinq.LogGeneral(category, action, String.Empty, description, null, null, null, null, null, null);
        }

        public static void LogGeneral(string category, string action, string result, string description)
        {
            LiquidViewLinq.LogGeneral(category, action, result, description, null, null, null, null, null, null);
        }
        
        public static void LogGeneral(string category, string action, string result, string descriptionFormat, params object[] data)
        {
            LiquidViewLinq.LogGeneral(category, action, result, String.Format(descriptionFormat, data), null, null, null, null, null, null);
        }


        public static bool TryImportFXrate(DateTime date, string baseCurrency, string subjectCurrency, decimal rate)
        {
            int retVal;
            try
            {
                retVal = LiquidViewLinq.ImportPriceFX(date, baseCurrency, subjectCurrency, rate);
                return retVal == 0;
            }
            catch(Exception e)
            {
#if DEBUG
                Console.WriteLine("TryImportFXrate - Caught exception " + e.Message);
#endif
            }
            return false;
        }


        public static void ImportPriceFromRTS(string hostName, string exchangeSymbol, DateTime date, string currency, string isin, string sedol, string symbol,
            decimal? open, decimal? high, decimal? low, decimal? close, decimal? settle, long? volume)
        {            
            LiquidViewLinq.ImportPriceStock(hostName, "RTS", exchangeSymbol, date, currency, isin, sedol, symbol, open, high, low, close, settle, volume);
        }

        static object _lock_TryImportPriceByUMTF = new object();
        public static bool TryImportPriceByUMTF(DateTime date, string umtf, string exchangeMIC, decimal? open, decimal? high, decimal? low, decimal? close, decimal? settle, long? volume, string text, out int retval)
        {
            retval = 0;
            try
            {
                lock(_lock_TryImportPriceByUMTF)                
                    retval = LiquidViewLinq.ImportPriceStockByUMTF(date, umtf, exchangeMIC, open, high, low, close, settle, volume, text);            
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
                retval = -1;
            }

            if (retval == 0)
                return true;

            return false;
        }



        public static bool TryImportPriceByUSSymbol(DateTime date, string symbol, string exchangeMIC, decimal? open, decimal? high, decimal? low, decimal? close, decimal? settle, long? volume, string text, out int retval)
        {
            retval = 0;
            try
            {
                retval = LiquidViewLinq.ImportPriceStockByUSSymbol(symbol, exchangeMIC, date, open, high, low, close, settle, volume, text);
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
                retval = -1;
            }

            if (retval == 0)
                return true;

            return false;
        }



        public static bool TryImportPriceByCanadaSymbol(DateTime date, string symbol, string exchangeMIC, decimal? open, decimal? high, decimal? low, decimal? close, decimal? settle, long? volume, string text, out int retval)
        {
            retval = 0;
            try
            {
                retval = LiquidViewLinq.ImportPriceStockByCanadaSymbol(symbol, exchangeMIC, date, open, high, low, close, settle, volume, text);
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
                retval = -1;
            }

            if (retval == 0)
                return true;

            return false;
        }


        public static bool TryImportPriceByOptionSymbol(DateTime date, string symbol, string currency, string exchangeMIC, decimal? open, decimal? high, decimal? low, decimal? close, decimal? settle, long? volume, string text, out int retval)
        {
            retval = 0;
            try
            {
                retval = LiquidViewLinq.ImportPriceByOptionSymbol(symbol, currency, exchangeMIC, date, open, high, low, close, settle, volume, text);
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
                retval = -1;
            }

            if (retval == 0)
                return true;

            return false;
        }


        public static bool TryImportSplitByUMTF(string umtf, DateTime date, int recieves, int forEvery, out int retval)
        {
            retval = 0;
            try
            {
                retval = LiquidViewLinq.ImportStockSplitByUMTF(date, umtf, recieves, forEvery);
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
                retval = -1;
            }

            if (retval == 0)
                return true;

            return false;
        }



        public static bool TryImportSplitByUSSymbol(string symbol, string market, DateTime date, int recieves, int forEvery, out int retval)
        {
            retval = 0;
            try
            {
                retval = LiquidViewLinq.ImportStockSplitByUSSymbol(symbol, market, date, recieves, forEvery);
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
                retval = -1;
            }

            if (retval == 0)
                return true;

            return false;
        }



        public static bool TryImportSplitByCanadaSymbol(string symbol, DateTime date, int recieves, int forEvery, out int retval)
        {
            retval = 0;
            try
            {
                retval = LiquidViewLinq.ImportStockSplitByCanadaSymbol(symbol, date, recieves, forEvery);
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
                retval = -1;
            }

            if (retval == 0)
                return true;

            return false;
        }


        public static bool TryGetOptionsSymbols(DateTime fromDate, string currency, out List<string> symbols)
        {
            try
            {
                symbols = LiquidViewLinq.ViewInstrumentsOptions.Where(a => a.Currency == currency && a.ExpiryDate >= fromDate).Select(a => a.Symbol).ToList();
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
                symbols = new List<string>();
            }
            return false;
        }

        public static int ImportInstrumentStock(string marketMIC, string currency, string isin, string sedol, string umtf, string symbol,
            string name, string cusip, string index, string bloomberg, string reuters, int? settlementDays, bool isRefresh, out int? stockId)
        {
            stockId = null;
            return LiquidViewLinq.ImportInstrumentStock(
                marketMIC,
                currency,
                isin,
                sedol,
                umtf,
                symbol,
                name,
                cusip,
                index,
                bloomberg,
                reuters,
                settlementDays,
                isRefresh,
                ref stockId);
        }


        /// <summary>
        /// Inserts a dividend into Liquid View
        /// </summary>
        /// <param name="marketMIC"></param>
        /// <param name="isin"></param>
        /// <param name="sedol"></param>
        /// <param name="currency"></param>
        /// <param name="divExDate"></param>
        /// <param name="divAmount"></param>
        /// <param name="divCurrency"></param>
        /// <param name="divRecordDate"></param>
        /// <param name="divPayDate"></param>
        /// <returns>0 on insert, 1 on already exists, -2 on currency failure, -3 on ISIN failure, -1 on unknown excpetion</returns>
        public static int ImportDividendByISIN(string isin, string sedol, string currency, DateTime divExDate, decimal divAmount, string divCurrency, DateTime? divRecordDate, DateTime? divPayDate)
        {
            return LiquidViewLinq.ImportDividendByISIN(isin, sedol, currency, divExDate, divAmount, divCurrency, divRecordDate, divPayDate);
        }


        /// <summary>
        /// Inserts a dividend into Liquid View
        /// </summary>
        /// <param name="umtf"></param>
        /// <param name="divExDate"></param>
        /// <param name="divAmount"></param>
        /// <param name="divCurrency"></param>
        /// <param name="divRecordDate"></param>
        /// <param name="divPayDate"></param>
        /// <returns>0 on insert, 1 on already exists, -2 on currency failure, -3 on UMTF failure, -1 on unknown excpetion</returns>
        public static int ImportDividendByUMTF(string umtf, DateTime divExDate, decimal divAmount, string divCurrency, DateTime? divRecordDate, DateTime? divPayDate)
        {
            return LiquidViewLinq.ImportDividendByUMTF(umtf, divExDate, divAmount, divCurrency, divRecordDate, divPayDate);
        }


        public static int ImportInstrumentStockListing(int stockId, string exchangeMIC, string localCurrency, string tickSizeName, string symbol,
            string bloomberg, string reuters, out int? listingId)
        {
            listingId = null;
            return LiquidViewLinq.ImportInstrumentStockListing(
                stockId,
                exchangeMIC,
                localCurrency,
                tickSizeName,
                symbol,
                bloomberg,
                reuters,
                ref listingId);
        }


        public static int ImportTickSize(string tickSizeName, string exchangeMIC, decimal? lowerPricelimit, decimal tickvalue, out long? tickSizeId)
        {
            tickSizeId = null;
            return LiquidViewLinq.ImportTickSize(tickSizeName, exchangeMIC, lowerPricelimit, tickvalue, ref tickSizeId);
        }


        /*
        public static void ImportTradeStockFromFTEN(string hostName, string hostOrderId, string hostTradeId, string exchangeSymbol, string exchangeOrderId, 
            string exchangeTradeId, string accountId, string currency, string symbol, decimal price, long volume, DateTime tradeTime, 
            string counterparty, string bic, bool? isAggressor, bool? isManual, bool? isInternal, string marketSegment, string brokerCode, string tradeText)
        {
            GetInstrumentStockDetailsFromSymbolResult instrument;
            if (TryGetInstrumentStockDetails(symbol, currency, out instrument))
            {
                exchangeTradeId = exchangeSymbol + "-" + symbol;

                Linq.ImportTrade('S', hostName, "FTEN", hostOrderId, hostTradeId, exchangeSymbol, exchangeOrderId, exchangeTradeId, accountId, currency, instrument.ISIN, instrument.Sedol, String.Empty, symbol, null,
                null, null, volume, price, tradeTime, counterparty, bic, isAggressor, isManual, isInternal, marketSegment, brokerCode, null, tradeText, null);
            }
            else
            {
                throw new ApplicationException(String.Format("Cannot find instument details for {0} {1} {2}, insert failed.", exchangeSymbol, currency, symbol));
            }
        }
        */

        public static void ImportTradeStockFromRTS(string hostName, string hostOrderId, string hostTradeId, string rtdExchangeSymbol, string exchangeOrderId,
            string exchangeTradeId, string accountId, string currency, string isin, string sedol, string symbol, decimal price, long volume, DateTime tradeTime,
            string counterparty, string bic, bool? isAggressor, bool? isManual, bool? isInternal, string marketSegment, string brokerCode, string tradeText)
        {
            LiquidViewLinq.ImportTrade('S', hostName, "RTS", hostOrderId, hostTradeId, rtdExchangeSymbol, exchangeOrderId, exchangeTradeId, accountId, currency, isin, sedol, String.Empty, symbol, null,
                null, null, volume, price, tradeTime, counterparty, bic, isAggressor, isManual, isInternal, marketSegment, brokerCode, null, tradeText, null);
        }


        public static void ImportTradeUSStock(
            string hostName, 
		    string hostOrderId, 
		    string hostTradeId, 
		    string exchangeMIC, 
		    string exchangeOrderId, 
		    string exchangeTradeId, 
		    string accountId, 
		    string symbol, 
		    long quantity, 
		    decimal price, 
		    DateTime tradeTime, 
		    string counterpartyCode, 
		    System.Nullable<bool> isAggressor)
        {
            try
            {
                LiquidViewLinq.ImportTradeUSStock(hostName, hostOrderId, hostTradeId, exchangeMIC, exchangeOrderId, exchangeTradeId, accountId, symbol, quantity, price, tradeTime, counterpartyCode, isAggressor, false, false, false, null, null, null, null, null, null);
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
            }
        }

        public static void ImportTradeUSStock(
            string hostName, 
			string hostOrderId, 
			string hostTradeId, 
			string exchangeMIC, 
			string exchangeOrderId, 
			string exchangeTradeId, 
			string accountId, 
			string symbol, 
			long quantity, 
			decimal price, 
			DateTime tradeTime, 
			string counterpartyCode, 
			System.Nullable<bool> isAggressor, 
			System.Nullable<bool> isManual, 
			System.Nullable<bool> isInternal, 
			System.Nullable<bool> isHidden, 
			string tradeType, 
			string brokerCode, 
			string tradeText, 
			string routedExchangeMIC, 
			string tradeFlags, 
			string userText)
        {
            try
            {
                LiquidViewLinq.ImportTradeUSStock(hostName, hostOrderId, hostTradeId, exchangeMIC, exchangeOrderId, exchangeTradeId, accountId, symbol, quantity, price, tradeTime, counterpartyCode, isAggressor, isManual, isInternal, isHidden, tradeType, brokerCode, tradeText, routedExchangeMIC, tradeFlags, userText);
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
            }
        }


        public static bool TryGetInstrumentStock(string marketMIC, string isin, string currencyId, string sedol, string symbol, out int? instrumentId)
        {
            instrumentId = -1;

            int result = -1;

            result = LiquidViewLinq.GetInstrumentStock(marketMIC, currencyId, isin, sedol, symbol, null, null, ref instrumentId);

            return (result == 0 && instrumentId != -1);
        }


        /// <summary>
        /// Try and get the matching instrumentId for a given Reuters Identifier Code
        /// </summary>
        /// <param name="ric">Reuters Identifier Code</param>
        /// <param name="instrumentId">The matching instrumentId</param>
        /// <returns>True when a single stock for found for a given ric</returns>
        public static bool TryGetInstrumentStock(string ric, out int instrumentId)
        {
            try
            {
                InstrumentsStock stock = LiquidViewLinq.InstrumentsStocks.Where(a => a.Reuters == ric).SingleOrDefault();

                if (stock != default(InstrumentsStock))
                {
                    instrumentId = stock.StockId;
                    return true;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
            }

            instrumentId = -1;

            return false;
        }

        /// <summary>
        /// Try and get the matching instrumentStock for a given Reuters Identifier Code
        /// </summary>
        /// <param name="ric">Reuters Identifier Code</param>
        /// <param name="stock">The matching instrumentStock</param>
        /// <returns>True when a single stock for found for a given ric</returns>
        public static bool TryGetInstrumentStock(string ric, out InstrumentsStock stock)
        {
            stock = default(InstrumentsStock);
            try
            {
                stock = LiquidViewLinq.InstrumentsStocks.Where(a => a.Reuters == ric).SingleOrDefault();

                if (stock != default(InstrumentsStock))                
                    return true;
                
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
            }

            return false;
        }

        public static bool TryCreateInstrumentStock(string marketMIC, string currency, string isin, string sedol, string symbol, string stockName, string cusip, out InstrumentsStock stock)
        {
            int? stockId = 0;
            stock = default(InstrumentsStock);

            try
            {
                if (LiquidViewLinq.GetInstrumentStock(marketMIC, currency, isin, sedol, symbol, stockName, cusip, ref stockId) >= 0
                    && stockId.HasValue)
                {
                    stock = LiquidViewLinq.InstrumentsStocks.Where(x =>
                                    x.StockId == stockId.Value
                                ).SingleOrDefault();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
                return false;
            }
        }

        public static bool TryCreateInstrumentStock(string ric, string currency, string isin, string sedol, string stockName, string cusip, out InstrumentsStock stock)
        {
            int? stockId = 0;
            stock = default(InstrumentsStock);
            try
            {
                string marketMIC = LiquidViewLinq.GetMICfromRIC(ric);
                ric = ric.Substring(0, ric.IndexOf('.'));

                if (LiquidViewLinq.GetInstrumentStock(marketMIC, currency, isin, sedol, ric, stockName, cusip, ref stockId) >= 0
                    && stockId.HasValue)
                {
                    stock = LiquidViewLinq.InstrumentsStocks.Where(x =>
                                    x.StockId == stockId.Value
                                ).SingleOrDefault();
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
                return false;
            }
        }

        /// <summary>
        /// Try and get the matching instrumentStock for a given currency, isin & sedol
        /// </summary>
        /// <param name="currency">Currency string GBP, EUR, USD etc</param>
        /// <param name="isin">GB0003456789</param>
        /// <param name="sedol">023456</param>
        /// <param name="stock">The matching stock if found</param>
        /// <returns>True when a single stock is found</returns>
        public static bool TryGetInstrumentStock(string currency, string isin, string sedol, string symbol, out InstrumentsStock stock)
        {
            stock = default(InstrumentsStock);

            try
            {
                if (symbol == null)
                {
                    if (isin != null)
                    {
                        if (currency != null)
                        {
                            if (sedol != null)
                            {
                                stock = LiquidViewLinq.InstrumentsStocks.Where(x =>
                                    x.ISIN == isin
                                    && x.Sedol == sedol
                                    && x.Instrument1.Symbol == currency
                                ).SingleOrDefault();
                            }
                            else if (sedol == null)
                            {
                                stock = LiquidViewLinq.InstrumentsStocks.Where(
                                    (x) =>
                                        x.ISIN == isin
                                        && x.Instrument1.Symbol == currency
                                    ).SingleOrDefault();
                            }
                        }
                    }
                }
                else // symbol != null
                {
                    if (isin == null)
                    {
                        if (currency == null)
                        {

                        }
                        else
                        {
                            if (sedol == null)
                            {
                                stock = LiquidViewLinq.InstrumentsStocks.Where(
                                    (x) =>
                                        x.Instrument1.Symbol == currency
                                        && x.Instrument.Symbol == symbol
                                    ).SingleOrDefault();
                            }
                            else
                            {
                                stock = LiquidViewLinq.InstrumentsStocks.Where(
                                    (x) =>
                                        x.Sedol == sedol
                                        && x.Instrument.Symbol == symbol
                                        && x.Instrument1.Symbol == currency
                                    ).SingleOrDefault();
                            }
                            
                        }
                    }
                }
                if (stock != default(InstrumentsStock))
                    return true;

            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
            }

            return false;
        }

        /// <summary>
        /// Try and get the matching instrumentStock for a given Reuters Identifier Code
        /// </summary>
        /// <param name="ric">Reuters Identifier Code</param>
        /// <param name="stock">The matching instrumentStock</param>
        /// <returns>True when a single stock for found for a given ric</returns>
        public static bool TryGetInstrumentStockUS(string isin, out InstrumentsStock stock)
        {
            stock = null;

            try
            {
                stock = LiquidViewLinq.InstrumentsStocks.Where(a => a.ISIN == isin && a.CurrencyId == CURRENCYID_USD).SingleOrDefault();

                if (stock != default(InstrumentsStock))
                    return true;
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
            }

            return false;
        }


        public static void UpdateInstrumentStock(InstrumentsStock stock, string isin, string sedol, string ric, string umtf, string sterlingSymbol)
        {
            InstrumentsStock update = LiquidViewLinq.InstrumentsStocks.Where(a => a == stock).Single();
            if (isin != null && isin != String.Empty) update.ISIN = isin;
            if (ric != null && ric != String.Empty) update.Reuters = ric;
            if (sedol != null && sedol != String.Empty) update.Sedol = sedol;
            if (umtf != null && umtf != String.Empty) update.UMTF = umtf;
            if (sterlingSymbol != null && sterlingSymbol != String.Empty) update.SterlingTrader = sterlingSymbol;
            LiquidViewLinq.SubmitChanges();
        }


        public static bool TryRunAlertReconciliationNewedgeAssetAllocationEmail(DateTime date)
        {
            try
            {
                return LiquidViewLinq.RunAlertReconciliationNewedgeAssetAllocationEmail(date) == 0 ? true : false;
            }
            catch(Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
            }
            return false;
        }


        public static bool TryImportNewedgeAssetValuation(NewedgeAssetValuation item)
        {
            try
            {
                LiquidViewLinq.NewedgeAssetValuations.InsertOnSubmit(item);
                LiquidViewLinq.SubmitChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
                return false;
            }
            return true;
        }

        public static bool TryImportNewedgeAssetValuation(IEnumerable<NewedgeAssetValuation> items)
        {
            try
            {
                LiquidViewLinq.NewedgeAssetValuations.InsertAllOnSubmit(items);
                LiquidViewLinq.SubmitChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
                return false;
            }
            return true;
        }
        
        public static bool TryRemoveNewedgeAssetValuation(DateTime date, string portfolio)
        {
            try
            {
                var remove = LiquidViewLinq.NewedgeAssetValuations.Where(a => a.ValuationDate == date && a.Portfolio == portfolio);
                LiquidViewLinq.NewedgeAssetValuations.DeleteAllOnSubmit(remove);
                LiquidViewLinq.SubmitChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
                return false;
            }
            return true;
        }


        public static bool TryImportNewedgeDailyTrades(IEnumerable<NewedgeDailyTrade> items)
        {
            try
            {
                LiquidViewLinq.NewedgeDailyTrades.InsertAllOnSubmit(items);
                LiquidViewLinq.SubmitChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
                return false;
            }
            return true;
        }

        public static bool TryRemoveNewedgeDailyTrades(DateTime date, string portfolio)
        {
            try
            {
                var remove = LiquidViewLinq.NewedgeDailyTrades.Where(a => a.TradeDate == date && a.Portfolio == portfolio);
                LiquidViewLinq.NewedgeDailyTrades.DeleteAllOnSubmit(remove);
                LiquidViewLinq.SubmitChanges();
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
                return false;
            }
            return true;
        }


        public static bool TryGetNextTradeId(string hostName, out long tradeId)
        {
            long? tradeIdNullable = null;

            int result = -1;

            result = LiquidViewLinq.GetTradeIdByHostName(hostName, ref tradeIdNullable);

            if (result != 0 || !tradeIdNullable.HasValue)
            {
                tradeId = -1;
                return false;
            }

            tradeId = tradeIdNullable.Value;
            return true;
        }


        public static bool TrySetNextTradeId(string hostName, long tradeId)
        {
            try
            {
                LiquidViewLinq.SetTradeIdByHostName(hostName, tradeId);
                return true;
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
                return false;
            }
        }


        public static bool TryGetInstrumentStockDetails(int instrumentId, out string marketMIC, out string currency, out string symbol)
        {

            GetInstrumentStockDetailsResult result = LiquidViewLinq.GetInstrumentStockDetails(instrumentId).SingleOrDefault();
            if (result != default(GetInstrumentStockDetailsResult))
            {
                marketMIC = result.MarketMIC;
                currency = result.Currency;
                symbol = result.Symbol;
                return true;
            }

            marketMIC = string.Empty;
            currency = string.Empty;
            symbol = string.Empty;
            return false;
        }


        public static bool TryGetInstrumentStockDetails(string UMTF, string currency, out GetInstrumentStockDetailsFromSymbolResult instrument)
        {
            instrument = null;

            string marketMIC;

            switch (UMTF[UMTF.Length - 1])
            {
                case 'l':
                    marketMIC = "XLON"; break;
                case 'a':
                    marketMIC = "XAMS"; break;
                case 'd':
                    marketMIC = "XETR"; break;
                case 'c':
                    marketMIC = "XCSE"; break;
                case 'b':
                    marketMIC = "XBRU"; break;
                case 'u':
                    marketMIC = "XLIS"; break;
                case 'p':
                    marketMIC = "XPAR"; break;
                case 'h':
                    marketMIC = "XHEL"; break;
                case 'i':
                    marketMIC = "XDUB"; break;
                case 'e':
                    marketMIC = "XMAD"; break;
                case 'm':
                    marketMIC = "XMIL"; break;
                case 'o':
                    marketMIC = "XOSL"; break;
                case 's':
                    marketMIC = "XSTO"; break;
                case 'z':
                    marketMIC = "XSWX"; break;
                default:
                    return false;
            }

            if (currency == "GBX")
                currency = "GBP";

            instrument = LiquidViewLinq.GetInstrumentStockDetailsFromSymbol(UMTF).Where(i => i.MarketMIC == marketMIC && i.Currency == currency).SingleOrDefault();
            if (instrument != default(GetInstrumentStockDetailsFromSymbolResult))
                return true;

            return false;
        }


        public static bool TryGetInstrumentStockDetails(int instrumentId, out GetInstrumentStockDetailsResult instrument)
        {
            instrument = LiquidViewLinq.GetInstrumentStockDetails(instrumentId).SingleOrDefault();
            if (instrument != default(GetInstrumentStockDetailsResult))
                return true;

            instrument = null;

            return false;
        }


        public static bool TryGetInstrumentStockDetailsAll(int instrumentId, out GetInstrumentStockDetailsAllResult instrument)
        {
            instrument = LiquidViewLinq.GetInstrumentStockDetailsAll(instrumentId).SingleOrDefault();

            if (instrument != default(GetInstrumentStockDetailsAllResult))
                return true;

            instrument = null;

            return false;
        }


        public static bool TryGetMICFromRTDExchange(string rtdExchange, out string marketMIC, out string exchangeMIC)
        {
            string moe = String.Empty;
            exchangeMIC = String.Empty;
            marketMIC = String.Empty;
            return 0 == LiquidViewLinq.GetMICSbyHostType("RTD", rtdExchange, ref exchangeMIC, ref marketMIC, ref moe);

            /*
            switch (rtdExchange)
            {
                case "LSE":
                    marketMIC = "XLON";
                    exchangeMIC = "XLON";
                    return true;
                case "XLON":
                    marketMIC = "XLON";
                    exchangeMIC = "CHIX";
                    return true;
                case "TLON":
                    marketMIC = "XLON";
                    exchangeMIC = "TRQX";
                    return true;
                case "BLON":
                    marketMIC = "XLON";
                    exchangeMIC = "BATE";
                    return true;
                case "AEX":
                    marketMIC = "XAMS";
                    exchangeMIC = "XAMS";
                    return true;
                case "XAMS":
                    marketMIC = "XAMS";
                    exchangeMIC = "CHIX";
                    return true;
                case "TAMS":
                    marketMIC = "XAMS";
                    exchangeMIC = "TRQX";
                    return true;
                case "BAMS":
                    marketMIC = "XAMS";
                    exchangeMIC = "BATE";
                    return true;
                case "ENX":
                    marketMIC = "XPAR";
                    exchangeMIC = "XPAR";
                    return true;
                case "XPAR":
                    marketMIC = "XPAR";
                    exchangeMIC = "CHIX";
                    return true;
                case "TPAR":
                    marketMIC = "XPAR";
                    exchangeMIC = "TRQX";
                    return true;
                case "BPAR":
                    marketMIC = "XPAR";
                    exchangeMIC = "BATE";
                    return true;
                case "XMIL":
                    marketMIC = "XMIL";
                    exchangeMIC = "CHIX";
                    return true;
                case "TMIL":
                    marketMIC = "XMIL";
                    exchangeMIC = "TRQX";
                    return true;
                case "BMTA":
                    marketMIC = "XMIL";
                    exchangeMIC = "BATE";
                    return true;
                case "XETR":
                    marketMIC = "XETR";
                    exchangeMIC = "CHIX";
                    return true;
                case "TETR":
                    marketMIC = "XETR";
                    exchangeMIC = "TRQX";
                    return true;
                case "BETR":
                    marketMIC = "XETR";
                    exchangeMIC = "BATE";
                    return true;
                default:
                    marketMIC = String.Empty;
                    exchangeMIC = String.Empty;
                    return false;
            }
             */

        }


        public static List<ViewSummaryOpenPositionsWithClose> GetOpenPositions()
        {
            return LiquidViewLinq.ViewSummaryOpenPositionsWithCloses.ToList();
        }

        public static int GetMaxCashEntryId()
        {
            return LiquidViewLinq.ViewCashEntries.Where(a => a.CashType != "DIV").Select(a => a.EntryId).Max();
        }

        public static int GetMaxCashDivEntryId()
        {
            return LiquidViewLinq.ViewCashEntriesDivs.Where(a => a.CashType == "DIV").Select(a => a.EntryId).Max();
        }

        public static System.Data.Linq.Table<ViewCashEntry> GetCashEntries
        {
            get
            {
                return LiquidViewLinq.ViewCashEntries;
            }
        }

        public static System.Data.Linq.Table<ViewCashEntriesDiv> GetDivEntries
        {
            get
            {
                return LiquidViewLinq.ViewCashEntriesDivs;
            }
        }


        public static bool CheckAccountId(string accountId)
        {
            return true;
        }


        public static bool TryGetUserId(int userIdDNN, out int userId)
        {
            int? temp = LiquidViewLinq.GetUserIdFromUserIdDNN(userIdDNN);
            if (temp.HasValue)
            {
                userId = temp.Value;
                return true;
            }
            else
            {
                userId = 0;
                return false;
            }
        }


        public static bool TryGetUserRoleId(int userId, int roleId, out int userRoleId)
        {
            int? temp = LiquidViewLinq.GetUserRoleId(userId, roleId);
            if (temp.HasValue)
            {
                userRoleId = temp.Value;
                return true;
            }
            else
            {
                userRoleId = 0;
                return false;
            }
        }

        public static bool CheckUserRole(int userId, int roleId)
        {
            int? temp = LiquidViewLinq.GetUserRoleId(userId, roleId);
            if (temp.HasValue)
                return true;            

            return false;
        }

        public static bool CheckUserRoleDNN(int userIdDNN, int roleId)
        {
            int userId;
            if (TryGetUserId(userIdDNN, out userId))
            {
                int? temp = LiquidViewLinq.GetUserRoleId(userId, roleId);
                if (temp.HasValue)
                    return true;
            }

            return false;
        }


        public static int UpdateInstrumentStockUSCanada(string marketMIC, string currency, string symbol, string name, int settlementDays, out int? stockId)
        {
            stockId = null;
            return LiquidViewLinq.ImportInstrumentStock(
                marketMIC,
                currency,
                null,
                null,
                null,
                symbol,
                name,
                null,
                null,
                null,
                null,
                settlementDays,
                false,
                ref stockId);
        }

        public static bool TryUpdateInstrumentStockUSCanada(string marketMIC, string currency, string symbol, string name, int settlementDays, out int? stockId, out int retVal)
        {
            stockId = null;
            retVal = -1;
            try
            {
                retVal = LiquidViewLinq.ImportInstrumentStock(
                    marketMIC,
                    currency,
                    null,
                    null,
                    null,
                    symbol,
                    name,
                    null,
                    null,
                    null,
                    null,
                    settlementDays,
                    false,
                    ref stockId);
                return retVal == 0;
            }
            catch(Exception e)
            {
#if DEBUG
                System.Diagnostics.Debug.WriteLine("TryUpdateInstrumentStockUSCanada Caught Exception " + e.Message);
#endif
            }
            return false;
        }

        public static bool FileImportIsFileImported(string source, string filename)
        {
            try
            {
                if (LiquidViewLinq.LogsFileImports.Count(a => a.LogSource == source && a.Filename == filename) != 0)
                    return true;
            }
            catch (Exception e)
            {
                Console.WriteLine("Caught Exception: " + e);
            }
            return false;
        }

        public static void FileImportRegisterFile(string source, string filename)
        {
            LogsFileImport row = new LogsFileImport() { LogSource = source, Filename = filename, TimeStamp = DateTime.Now };
            LiquidViewLinq.LogsFileImports.InsertOnSubmit(row);
            LiquidViewLinq.SubmitChanges();
        }
    }
}
